package com.authority.framework.base.Thread;

/**
 * @program: authority2
 * @description: 项目启动启动此线程，清空历史在线用户
 * @author: Mr.Yan
 * @create: 2019-01-09 11:25
 **/

import com.authority.RunApplication;
import com.authority.framework.base.util.SpringUtils;
import com.authority.framework.web.service.SysUserOnlineService;
import org.springframework.boot.SpringApplication;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class onlineThread extends Thread {

    // 线程锁，防止死循环和死等待 利用tryLock
    public static ReentrantLock lock = new ReentrantLock();

    public onlineThread(String name) {
        super(name);

    }
    //  线程开始
    public void run() {
        try {
            if (lock.tryLock(1, TimeUnit.SECONDS)) {//设置获取锁的等待时长1秒
                System.out.println(Thread.currentThread().getName() + "获 得 锁");
                //SpringApplication.run(RunApplication.class);
                System.out.println(Thread.currentThread().getName() + "开始清空在线用户历史数据");
                Integer deletNum = SpringUtils.getBean(SysUserOnlineService.class).commonDelete("system/SysUserOnlineSql.deleteAll",null);
                System.out.println(Thread.currentThread().getName() + "清空在线用户历史数据完成，共清理" + deletNum + "条历史记录" );
            } else {
                System.out.println(Thread.currentThread().getName() + "未 获 得 锁");
            }
        } catch (Exception e) {
            System.out.println(Thread.currentThread().getName() + "出 项 异 常");
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释 放 锁");
            lock.unlock();//释放锁
        }
    }
    // 测试方法
    public static void main(String[] args) {
        Thread t1 = new onlineThread("springboot And beetlsql And freemarker :  ");
        t1.start();
    }
}

